/*
 * logger.cpp
 *
 *  Created on: 08/05/2012
 *      Author: federico
 */

#include "logger.h"
#include <time.h>
#include "../common/StringUtils.h"
#include "../common/ArchivoIni.h"

using namespace std;

CLogger* CLogger::m_instance = NULL;
bool CLogger::m_useLevelColors = false;

void CLogger::create(std::string processName, bool useLevelColors)
{
	if(m_instance != NULL)
		delete m_instance;

	ArchivoIni arch("config.ini");
	string useColours = arch.getValue("log_colours");
	bool usecol = false;
	if (!useColours.empty()) {
		usecol = StringUtils::StringToNumber<bool>(useColours);
	}
	m_instance = new CLogger(processName);
	m_useLevelColors = usecol || useLevelColors;
}

void CLogger::destroy()
{
	if(m_instance != NULL)
		delete m_instance;

	m_instance = NULL;
}

CLogger::CLogger(std::string processName):m_file("log.txt"),m_ProcessName(processName)
{
}

CLogger::CLogger(CLogger&):m_file("log.txt")
{
}

CLogger::~CLogger()
{
	//m_logFile.close();
};


void CLogger::log( string message, int msgLevel, ColorCode color )
{
	if(m_instance)
	{
		// ToDo: Initialize CLogger with process info (pid, name, etc)
		std::stringstream sAux;

		Date currentTime = Date::now();

		if( msgLevel >= m_instance->m_logguerLevel.m_Level )
		{
			sAux <<"["<<m_instance->m_ProcessName<<","<<LogLevelEnum::toString(msgLevel)
				<<","<<currentTime.toString()<<"]" <<message<<endl;

			if (color == color::NO_COLOR && m_useLevelColors){
				std::cout << color::get(LogLevelEnum::toColor(msgLevel), color::BRIGHT)  << sAux.str();
			} else if (color != color::NO_COLOR) {
				std::cout << color::get(color, color::BRIGHT)  << sAux.str();
			} else {
				std::cout << sAux.str();
			}

			m_instance->m_file.write(sAux.str().c_str(), sAux.str().length());
		}
	}
	std::cout<<"\033[0m"<<std::endl;
}

void CLogger::setLevel ( int newLogLevel )
{
	if(m_instance)
		m_instance->m_logguerLevel.m_Level = newLogLevel;
}

int CLogger::getLevel ()
{
	if(m_instance)
		return m_instance->m_logguerLevel.m_Level;
	else
		return -1;
}
